package com.aikg.kgrag_java.controller;


import com.aikg.kgrag_java.repository.TaskRepository;
import com.aikg.kgrag_java.service.FileProcessor;
import com.aikg.kgrag_java.service.OcrService;
import lombok.AllArgsConstructor;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.aikg.kgrag_java.commom.TaskStatus;
import com.aikg.kgrag_java.pojo.entity.Task;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @Author tfan
 * @Description
 * @Date 2024/12/31 11:55
 **/
@RestController
@AllArgsConstructor
public class OcrController {

    @Autowired
    private OcrService ocrService;

    private final TaskRepository taskRepository;
    private final FileProcessor fileProcessor;

    /**
     * 单线程，上传即识别
     * 弃用
     * @param file
     * @return
     * @throws TesseractException
     * @throws IOException
     */
    @PostMapping(value = "/recognize")
    public String recognizeImage(@RequestParam("file") MultipartFile[] file) throws TesseractException, IOException {
        // 调用OcrService中的方法进行文字识别
        return ocrService.recognizeText(file);
    }

    /**
     * 上传文件并异步处理
     * 返回任务 ID，根据任务 ID 查询任务状态
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile[] file) {
        // 生成唯一任务 ID
        String taskId = UUID.randomUUID().toString();

        // 创建任务并存储
        Task task = new Task();
        task.setTaskId(taskId);
        task.setStatus(TaskStatus.PENDING);
        task.setCreatedTime(LocalDateTime.now());
        if (!taskRepository.save(task)) {
            return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body("服务器繁忙，请稍后再试。");
        }

        // 异步处理文件
        fileProcessor.processFile(taskId, file);

        return ResponseEntity.ok(taskId);
    }


    /**
     * 根据任务 ID 查询任务状态
     * @param taskId
     * @return
     */
    @GetMapping("/{taskId}")
    public ResponseEntity<Task> getTaskStatus(@PathVariable String taskId) {
        Task task = taskRepository.findById(taskId);
        if (task == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(task);
    }
}
